package com.boot.main.shiro;

import com.boot.main.jwt.JwtToken;
import com.boot.main.jwt.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MyRealm  extends AuthorizingRealm {
    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean supports(AuthenticationToken token){
        return token instanceof JwtToken;
    }
    // 请求读写权限
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection org){
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermission("read");
        log.info(org.toString());
        return simpleAuthorizationInfo;
    }

    // 请求身份认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException{
        String token = (String) authenticationToken.getCredentials();
        if(!jwtUtils.verifyToken(token) || jwtUtils.isExpire(token)){
            throw new AuthenticationException("token已失效，请重新登录");
        }
        String username = JwtUtils.getUsername(token);
//        String username = ((UsernamePasswordToken) authenticationToken).getUsername();
//        String auToken = String.valueOf(((UsernamePasswordToken) authenticationToken).getPassword());
//        log.info(auToken);
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username, token, getName());
        return simpleAuthenticationInfo;
    }
}
